package com.itheima.controller;

import com.itheima.bean.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.解决请求和响应中文乱码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //2.获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //3.调用service层方法进行登录,得到User对象
        UserService userService = new UserServiceImpl();
        User user = userService.login(username, password);
        //4.判断user对象是否为null,如果为null说明登录失败,响应false
        if(user==null){
            response.getWriter().write("false");
        }else{
            //5.如果user不为null,说明登录成功,响应true
            //将用户信息保存到会话域对象Session中
            request.getSession().setAttribute("user",user);
            response.getWriter().write("true");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
